<template>
  <div class="v-field-group">
    <input
      ref="input"
      class="v-field-input"
      type="text"
      :name="name"
      :placeholder="placeholder"
      :disabled="disabled"
      :readonly="readonly"
      :maxlength="maxlength"
      :minlength="minlength"
      :value="currentValue"
      v-model="currentValue"
      @focus="handleFocus"
      @blur="handleBlur"
    >
    <label class="v-field-label" :class="{ 'v-field-hasVal': hasVal }">
      {{label}}
    </label>
  </div>
</template>

<script>
export default {
  name: 'Field',
  props: {
    value: [String, Number],
    type: String,
    label: String,
    name: String,
    disabled: Boolean,
    readonly: Boolean,
    placeholder: String,
    maxlength: Number,
    minlength: Number,
  },
  data() {
    return {
      currentValue: this.value,
      hasVal: false,
    }
  },
  watch: {
    value(val) {
      this.currentValue = val
    },
    currentValue(val) {
      if (val.length > 0) {
        this.hasVal = true
      } else {
        this.hasVal = false
      }

      this.$emit('input', val)
      this.$emit('on-change', val)
    },
  },
  methods: {
    handleInput(event) {
      this.setCurrentValue(event.target.value)
    },
    handleFocus(event) {
      this.$emit('focus', event)
    },
    handleBlur(event) {
      this.$emit('blur', event)
    },
    setCurrentValue(value) {
      if (value === this.currentValue) return
      this.currentValue = value
      this.$emit('input', value)
      this.$emit('change', value)
    },
  },
}
</script>

<style lang="scss">
.v-field-group {
  position: relative;
}

.v-field-input {
  -webkit-appearance: none;
  border-radius: 0;
  padding-top: 37px;
  padding-left: 12px;
  font-size: 18px;
  width: 100%;
  height: 72px;
  display: block;
  border: 0;
  border-bottom: 1px solid #e7e7e7;
  background-color: #fff;
  &:focus ~ label {
    color: #009688;
  }
}

.v-field-label {
  color: #9B9B9B;
  font-size: 16px;
  line-height: 19px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 12px;
  top: 26px;
  transition: 200ms ease-in-out all;
}

.v-field-hasVal {
  top: 16px;
  font-size: 12px;
  color: #009688;
}

.hasVal {
  top: 16px;
  font-size: 12px;
}
</style>
